package com.xxy.shiro.config;

import com.xxy.shiro.entity.User;
import com.xxy.shiro.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.Set;


/**
 * 自定义 Realm
 */
public class CustomizeRealm extends AuthorizingRealm {

    @Resource
    UserService userService;


    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        // 通过输入的用户名 authenticationToken.getPrincipal() 和 数据库 user 检验
        User user = userService.findByName((String) authenticationToken.getPrincipal());
        System.out.println(user.getUsername());
        if (user == null){ // 返回 UnknownAccountException 用户名错误
            return null;
        }
        // 密码校验
        return new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());

    }
}
